package com.icecloud.cloud.upms.conf.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.icecloud.cloud.upms.common.utils.RestfulResponseBody;

/**
 * 登录验证
* @author penghaozhong E-mail:penghaozhong@163.com
* @version 创建时间：2016年8月3日 下午5:02:26
* 
*/
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {
	protected final Log logger = LogFactory.getLog(getClass());

	
	
	public RestAuthenticationFailureHandler() {
		super();
	}



	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		exception.printStackTrace();
		RestfulResponseBody body = new RestfulResponseBody();
		if(exception instanceof BadCredentialsException){
			body.setReason("登陆失败：密码不正确！");
		}else{
			body.setReason("登陆失败："+exception.getMessage());
		}
		
		body.setResultFlag(0);
		PrintWriter writer;  
        response.setStatus(200);  
        writer = response.getWriter();  
        writer.write(new ObjectMapper().writeValueAsString(body));  
        writer.flush();  
        writer.close();
        
        logger.debug("登陆失败");

	}

}
